from dbmgr import DBMgr, DBMgrError
import popen2, socket

class SysMetrics:

    def __init__(self):
        self.db = DBMgr()
        self.connect_error = 0
        try:
            self.db.connect()
        except DBMgrError, e:
            print "database connection exception" 
            self.connect_error = 1
        self.hostname = socket.gethostname()

    def get_vmstat_metrics(self):
        (stdout, stdin, stderr) = popen2.popen3('vmstat 5 2')
        lines = stdout.readlines()
        last_line = lines[-1].rstrip()
        (self.r, self.b, self.swpd, self.free, self.buff, self.cache,\
            self.si, self.so, self.bi, self.bo, self.intrpt, \
            self.cs, self.us, self.sy, self.id, self.wa, self.st) = map(lambda x: int(x), last_line.split())

    def insert_vmstat_metrics(self):
        sql = "INSERT INTO vmstat_metrics (hostname, r, b, swpd, free, buff, cache,\
            si, so, bi, bo, intrpt, \
            cs, us, sy, id, wa, st) \
            VALUES ('%s', %d, %d, %d, \
            %d, %d, %d, \
            %d, %d, %d, %d, %d, \
            %d, %d, %d, %d, %d, %d)" % \
            (self.hostname, self.r, self.b, self.swpd,\
            self.free, self.buff, self.cache,\
            self.si, self.so, self.bi, self.bo, self.intrpt, \
            self.cs, self.us, self.sy, self.id, self.wa, self.st)
        self.db.execute(sql)

    def update_metrics(self):
        values = (
            ("pkg1", "ver11", 1000, 2000, 3000, 4000),
            ("pkg2", "ver22", 11, 22, 33, 43),
            ("pkg3", "ver33", 1, 222, 3, 4445),
            ("pkg4", "ver44", 1, 2, 3, 4444),
        )

        self.db.update_metrics(values)

    def get_all_metrics(self):
        return self.db.get_all_values("metrics")

    def get_top_metrics(self, top=3, order_by_index=5):
        rows = self.get_all_metrics()
        # Decorate-Sort-Undecorate (DSU) pattern
        r = [(row[order_by_index], row) for row in rows]
        r.sort(reverse=True)
        r = [row[1] for row in r]
            
        return r[:top]

if __name__ == "__main__":
    myapp = SysMetrics()
    myapp.get_vmstat_metrics()
    myapp.insert_vmstat_metrics()
